interface FontParameters {
  style: string; // 正常 - 斜体
  variant: string; // 正常 - 全大写 - 。。。
  weight: string; // 字体宽度
  size: string; // 字体大小
  lineHeight: string; // 行高
  family: string; // 字体集
}

const fontRegEx = new RegExp(
  [
    '^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)',
    '(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)',
    '(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)',
    '(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?',
    '(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))',
    '(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))',
    '?\\s*([-,\\"\\\'\\sa-z]+?)\\s*$',
  ].join(''),
  'i',
);
const fontRegExMatchIndex = ['style', 'variant', 'weight', 'size', 'lineHeight', 'family'];

/**
 * 从font中解析各项参数
 * @param fontSpec
 * @returns 解析出来的各项字体参数
 */
export function getFontParameters(fontSpec: string): FontParameters {
  const match = fontSpec.match(fontRegEx);
  const style: any = {
    lineHeight: 'normal',
    size: '16px',
    style: 'normal',
    weight: 'normal',
    variant: 'normal',
  };

  // 字体不对的时候，返回默认值
  if (!match) {
    return { ...style, family: 'sans-serif' };
  }

  for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) {
    const value = match[i + 1];
    if (value !== undefined) {
      style[fontRegExMatchIndex[i]] = value;
    }
  }
  style.families = style.family.split(/,\s?/);
  return style;
}

/**
 * 从字体参数中解析成string
 * @param font 字体参数
 * @returns 字体字符串
 */
export function getFontString(font: FontParameters) {
  return `${font.style} ${font.variant} ${font.weight} ${font.size} / ${font.lineHeight} ${font.family}`;
}
